
package network.udptools;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import model.data.MessagesFactory;
import network.Interface.NiController;
import network.udptools.Interface.UDPListenerInterface;

import cs.remoteapp.Message;
/**
 * @author Christelle SIAGO HAPPI
 * UDPListener : listening to the messages exchanged on the network
 */


public class UDPListener implements Runnable,UDPListenerInterface{

    private DatagramSocket socket;
    private boolean bListening;
    private NiController ni;
    
	public UDPListener(NiController ni) {
		this.bListening = true;
		this.ni=ni;
	}
	  
    /**
     * Manages start listening on the socket
     */
    public void StartListening() {

        boolean  bSucceded = false;
        while(!bSucceded)
        {
            try {
                socket = new DatagramSocket(UDPSettings.UDP_PORT_ECOUTE);
                bSucceded = true;
                (new Thread(this)).start();
            } 
            catch (SocketException socketCreationException) 
            {
                System.out.println("socketCreation : Failed \n"+socketCreationException);              
            }
        }
    }

    
    /**
    * Manages to stop listening on the socket
    */
    public void StopListening() {
        bListening = false;
    }

    
    /**
     * Manages executed by the thread code UDPListener
     */
    @Override
    public void run() {

        while(bListening) {

                byte[] streamByte = new byte[1500];
                DatagramPacket inPacket = new DatagramPacket(streamByte, streamByte.length);
                try {
                    socket.receive(inPacket);
                    Message recvMessage = MessagesFactory.getMessage(inPacket.getData());

                    if(recvMessage != null)
                       this.ni.receivedMessage(recvMessage,inPacket.getAddress());
                } 
                catch (Exception receiveExeption) {
                	System.out.println("Reception signal : failed \n"+receiveExeption);   
                }
        }
    }

}
